import React from "react";
import { useContext } from "react";
import { useEffect } from "react";
import { useState } from "react";
import {
  Avatar,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  TextField,
  Typography,
  Divider,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
} from "@mui/material";
import { renderCellExpand } from "../../../components/RenderCellExpand";
import { DataGrid } from "@mui/x-data-grid";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import Paper from "@mui/material/Paper";
import { flexbox } from "@mui/system";
import AddIcon from "@mui/icons-material/Add";
import PropTypes from "prop-types";
import { useTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
import { useSnackbar } from "notistack";
import { useMutation } from "@tanstack/react-query";
import TableHead from "@mui/material/TableHead";
import {
  DataGridPremium,
  GridToolbarContainer,
  GridToolbarExport,
} from "@mui/x-data-grid-premium";
import Dataform from "../../../components/Dataform";
import { TitleContext } from "../../../router";
import { GET_STUDENTS_URL } from "../../../constants/url";
import { POST_COURSECAPACITY_URL } from "../../../constants/url";
import Loading from "../../../components/loading";

//导出的完整类
export default function ShowCourse(props) {
  const nowTitle = useContext(TitleContext);
  const [thisCourse, setThiscourse] = useState([
    {
      name: "",
      teacher: "",
      capacity: "",
      college: "",
      credit: "",
      type: "",
      courseId: "",
      location: "",
    },
  ]);
  useEffect(() => {
    nowTitle.setnowTitle(3);
  }, []);
  const courseId = props.courseId;
  const courseInfo = props.courseInfo;
  const courseTime = props.courseTime;
  const [capacity, setCapacity] = useState();
  useEffect(() => {
    if (courseId && courseInfo) {
      courseInfo.map((val) => {
        if (val.id == courseId) {
          setThiscourse(
            val.status !== undefined
              ? {
                  ...val,
                }
              : {}
          );
        }
      });
    }
  }, [courseId, courseInfo]);

  //数据处理
  const [courseDate, setCourseDate] = useState();
  useEffect(() => {
    let content = "第";
    courseTime.forEach((ele1, index) => {
      if (ele1.id === courseId) {
        ele1.weeks.forEach((ele2, index) => {
          if (index != ele1.weeks.length - 1) {
            content += ele2 + ",";
            setCourseDate(content);
          } else {
            content += ele2 + "周需要上课";
            setCourseDate(content);
          }
        });
      }
    });
  }, []);

  //课程容量修改
  const {
    isLoading: updLoading,
    isSuccess: updSuccess,
    data: upddata,
    isError: updError,
    mutate: updMutate,
  } = useMutation(["updCourseCapacity"], mutateQueryFn);
  const [open, setOpen] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  const handleClick = () => {
    if (!capacity) {
      enqueueSnackbar("课程号不能为空", { variant: "warning" });
      return;
    }
    updMutate({
      url: POST_COURSECAPACITY_URL,
      params: { id: courseId, num: capacity },
      method: "post",
      useToken: true,
    });
    setOpen(false);
  };
  useEffect(() => {
    if (updSuccess) {
      if (upddata.data.code != 0) {
        enqueueSnackbar(upddata.data.data, { variant: "error" });
      } else {
        enqueueSnackbar("修改成功", { variant: "success" });
        const thisCourseF = thisCourse;
        setThiscourse({ ...thisCourseF, capacity: capacity });
      }
    }
  }, [updSuccess]);

  const [rows, setRows] = useState([]);
  // 获取选课列表
  const {
    data,
    isLoading: getLoading,
    mutate: getMutate,
    isSuccess: getSuccess,
  } = useMutation(["getStudent"], mutateQueryFn);
  useEffect(() => {
    if (courseId) {
      getMutate({
        url: GET_STUDENTS_URL,
        params: { id: courseId },
        method: "get",
        useToken: true,
      });
    }
  }, [courseId]);

  useEffect(() => {
    if (getSuccess) {
      setRows(
        data.data.data.data.map((val, key) =>
          val.name !== undefined
            ? {
                ...val,
              }
            : {}
        )
      );
    } else {
    }
  }, [getSuccess]);

  const columns = [
    {
      field: "id",
      headerName: "序号",
      flex: 1,
      editable: false,
    },
    {
      field: "userId",
      renderCell: renderCellExpand,
      headerName: "学号",
      flex: 3,
    },
    {
      field: "name",
      renderCell: renderCellExpand,
      headerName: "姓名",
      flex: 3,
    },
    {
      field: "gender",
      renderCell: renderCellExpand,
      headerName: "性别",
      flex: 2,
      // width: 150,
    },
    {
      field: "grade",
      renderCell: renderCellExpand,
      headerName: "年级",
      flex: 2,
    },

    {
      field: "major",
      renderCell: renderCellExpand,
      headerName: "所属专业",
      flex: 3,
    },
  ];
  return (
    <>
      {getLoading && (
        <Box
          sx={{
            width: "100%",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            minHeight: 600,
          }}
        >
          <Loading />
        </Box>
      )}
      {getSuccess && (
        <>
          <Paper
            sx={{
              mt: 1,
              display: "flex",
              float: "left",
              flexDirection: "column",
              width: "100%",
            }}
          >
            <Box sx={{ display: "flex", float: "left", flexDirection: "row" }}>
              {/* 左侧 */}
              <Box
                sx={{ display: "flex", flexDirection: "column", width: "25%" }}
              >
                <Box
                  sx={{
                    mt: 1,
                    marginLeft: 6,
                    marginBottom: 1,
                    display: "flex",
                    flexDirection: "column",
                  }}
                >
                  <span>课程名称:&nbsp;&nbsp;&nbsp;{thisCourse.name}</span>
                  <span>开课学院:&nbsp;&nbsp;&nbsp;{thisCourse.college}</span>
                  <span>授课地点:&nbsp;&nbsp;&nbsp;{thisCourse.location}</span>
                  <span>课程类型:&nbsp;&nbsp;&nbsp;{thisCourse.type}</span>
                </Box>
              </Box>
              {/* 右侧 */}
              <Box
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  marginTop: 1,
                  marginLeft: 30,
                  marginBottom: 1,
                }}
              >
                <span>课程号:&nbsp;&nbsp;&nbsp;{thisCourse.courseId}</span>
                <span>学分:&nbsp;&nbsp;&nbsp;{thisCourse.credit}</span>
                <span>开课周数:&nbsp;&nbsp;&nbsp;{courseDate}</span>
                <Box sx={{ display: "flex", flexDirection: "row" }}>
                  <span>课程容量:&nbsp;&nbsp;&nbsp;{thisCourse.capacity}</span>
                  <Button
                    size="small"
                    endIcon={<AddIcon />}
                    onClick={() => setOpen(true)}
                    sx={{ marginLeft: 2, mt: "-3px" }}
                  >
                    扩充容量
                  </Button>
                  <Dialog
                    open={open}
                    onClose={() => {
                      setOpen(false);
                    }}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                  >
                    <DialogTitle id="alert-dialog-title">扩充容量</DialogTitle>
                    <DialogContent sx={{ minWidth: 300, minHeight: 100 }}>
                      <DialogContentText id="alert-dialog-description">
                        <TextField
                          label="capacity*"
                          size="small"
                          sx={{ width: 130, mt: 2 }}
                          onChange={(e) => {
                            setCapacity(e.target.value);
                          }}
                          value={capacity}
                        />
                      </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                      <Button variant="contained" onClick={handleClick}>
                        保存
                      </Button>
                    </DialogActions>
                  </Dialog>
                </Box>
              </Box>
            </Box>
          </Paper>
          {/* 选课名单 */}
          <Box
            sx={{
              height: 460,
              mt: 2,
              display: "flex",
              float: "left",
              width: "100%",
            }}
          >
            <Dataform
              fileName={"考试申请列表"}
              rows={rows}
              // loading={getLoading}
              columns={columns}
            />
          </Box>
        </>
      )}
    </>
  );
}
